package com.xteam.xnetworkdisk.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xteam.xnetworkdisk.utils.IPIp2RegionUtils;
import com.xteam.xnetworkdisk.utilsinterface.IPUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class IPService {
    private final static IPUtils ipUtils = new IPIp2RegionUtils();

    public String[] getLocationByRequest(HttpServletRequest request) {
        String location = null;
        String clientIpAddress = null;
        // 获取 IP 地址对应的位置
        try {
            clientIpAddress = ipUtils.getClientIpAddress(request);

            // 获取 IP 地址对应的位置
            String locationResponse = ipUtils.getLocationByIp(clientIpAddress);
            // 解析 JSON 响应
            JSONObject jsonResponse = JSON.parseObject(locationResponse);

            // 检查状态
            String status = jsonResponse.getString("status");
            if ("fail".equalsIgnoreCase(status)) {
                // 如果状态为 "fail"，则设置 location 为空
                location = null;
            } else {
                String country = jsonResponse.getString("country");
                String regionName = jsonResponse.getString("regionName");
                String city = jsonResponse.getString("city");
                if(regionName.equals("0")){
                    regionName = "\"\"";
                }

                if(city.equals("0")){
                    city = "\"\"";
                }

                // 否则，设置实际的位置
                location = country  + "|" +  regionName + "|" +  city ;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return new String[]{clientIpAddress, location};
    }

    public String getDeviceByRequest(HttpServletRequest request){
        String deviceDetails = ipUtils.getDeviceDetails(request);
        return deviceDetails;
    }
}
